import { compressOptions, mainProgressNoticeType } from './../renderer/src/type'
import { BrowserWindow, IpcMainInvokeEvent } from 'electron'
import ffmpegPath from '@ffmpeg-installer/ffmpeg'
import ffprobePath from '@ffprobe-installer/ffprobe'
import ffmpeg from 'fluent-ffmpeg'
import path from 'path'
import { existsSync } from 'fs'
// 打包后修复路劲问题
ffmpeg.setFfmpegPath(ffmpegPath.path.replace('app.asar', 'app.asar.unpacked'))
ffmpeg.setFfprobePath(ffprobePath.path.replace('app.asar', 'app.asar.unpacked'))

export default class Ffmpeg {
  ffmpeg: ffmpeg.FfmpegCommand
  window: BrowserWindow
  constructor(
    private event: IpcMainInvokeEvent,
    private options: compressOptions
  ) {
    this.ffmpeg = ffmpeg(this.options.file.path)
    this.window = BrowserWindow.fromWebContents(this.event.sender)!
  }

  progressEvent(progress) {
    this.window.webContents.send(
      'mainProgressNotice',
      mainProgressNoticeType.PROGRESS,
      progress.percent
    )
  }
  error(err) {
    console.log('An error occurred: ' + err.message)
  }
  end() {
    this.window.webContents.send('mainProgressNotice', mainProgressNoticeType.END, 'end')
    // console.log('Processing finished !')
  }

  stop() {
    try {
      this.ffmpeg.kill('SIGKILL')
      this.window.webContents.send('mainProgressNotice', mainProgressNoticeType.STOP, '')
    } catch (error) {
      console.log(error)
    }
  }

  // 获取文件信息
  private getSaveFilePath() {
    const info = path.parse(this.options.file.path)
    return path.join(
      this.options.saveDirectory,
      `${info.name}-${this.options.size}-${this.options.fps}${info.ext}`
    )
  }

  private validate() {
    if (!existsSync(this.options.saveDirectory)) {
      // dialog.showErrorBox('温馨提示', '目录不存在？')
      this.window.webContents.send(
        'mainProgressNotice',
        mainProgressNoticeType.DIRECTORYCHECK,
        '目录不存在？'
      )
      return false
    }

    if (existsSync(this.getSaveFilePath())) {
      this.window.webContents.send('mainProgressNotice', mainProgressNoticeType.FILE_IS_EXISTS, '')
      return false
    }
    return true
  }
  run() {
    if (!this.validate()) return
    this.ffmpeg
      .videoCodec('libx264')
      .audioCodec('libmp3lame')
      .fps(this.options.fps)
      .size(this.options.size)
      .on('progress', this.progressEvent.bind(this))
      .on('error', this.error.bind(this))
      .on('end', this.end.bind(this))
      .save(this.getSaveFilePath())
  }
}
